from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import base64
import time
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.common.by import By


class AppProxy:
    proxy_host = ""
    proxy_port = "1080"
    username = ""
    password = ""
    protocol = "http"
    udid = ""
    driver =  None
    def __init__(self,driver, proxy_host, proxy_port , username , password,protocol = "http"):

        self.driver = driver
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.username = username
        self.password = password
        self.protocol = protocol


    def add_proxy(self):
        try:
            allow_notify = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '//android.view.View[@content-desc="添加代理"]'
            )))
            allow_notify.click()
            print("点击添加代理")
            # 等待并处理权限提示框

        except (TimeoutException, NoSuchElementException):
            print("没有找到添加代理按钮")
            source = self.driver.page_source
            print(source)

        try:
            # 定位目标 EditText
            element_xpath = ("//android.widget.FrameLayout[@resource-id='android:id/content']"
                             "/android.widget.FrameLayout/android.view.View/android.view.View"
                             "/android.view.View/android.view.View/android.view.View[2]"
                             "/android.widget.EditText[1]")

            elem = self.driver.find_element("xpath", element_xpath)

            # 检查是否可输入
            if elem.is_enabled() and elem.get_attribute("focusable") == "true":
                elem.click()
                elem.clear()
                elem.send_keys("myproxy1")
                print("✅ 输入成功：myproxy1")
            else:
                print("⚠️ 该文本框不可输入")

        except NoSuchElementException:
            print("❌ 未找到该文本框，请检查 XPath 是否正确")
        try:

            if self.protocol == "socks5":
                # // android.view.View[ @ content - desc = "socks5"]
                # 用 text 属性定位选项按钮
                xpath = f"//android.view.View[@text='http']/android.widget.Button"
                elem = self.driver.find_element("xpath", xpath)
                elem.click()

                xpath = '//android.view.View[@content-desc="socks5"]'
                elem = self.driver.find_element("xpath", xpath)
                elem.click()

        except NoSuchElementException:
            print(f"❌ 未找到选项: {self.protocol}")
        try:
            # 输入代理地址
            element_xpath = (
                '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.widget.EditText[2]')
            elem = self.driver.find_element("xpath", element_xpath)
            if elem.is_enabled() and elem.get_attribute("focusable") == "true":
                elem.click()
                elem.clear()
                elem.send_keys(self.proxy_host)
                print("✅ 输入成功：")
            else:
                print("⚠️该文本框不可输入")
        except:
            print("未找到代理地址输入框")
        try:
            # 输入代理端口
            element_xpath = (
                '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.widget.EditText[3]')
            elem = self.driver.find_element("xpath", element_xpath)
            if elem.is_enabled() and elem.get_attribute("focusable") == "true":
                elem.click()
                elem.clear()
                elem.send_keys(self.proxy_port)
                print('✅ 输入成功：'+self.proxy_port)
            else:
                print("⚠️该文本框不可输入")
        except:
            print("未找到代理地址输入框")
        if self.username != "":
            try:
                # 输入代理用户名
                element_xpath = (
                    '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.widget.EditText[4]')
                elem = self.driver.find_element("xpath", element_xpath)
                if elem.is_enabled() and elem.get_attribute("focusable") == "true":
                    elem.click()
                    elem.clear()
                    elem.send_keys(self.username)
                    print("✅ 输入成功："+self.username)
                else:
                    print("⚠️该文本框不可输入")
            except:
                print("未找到代理地址输入框")
        if self.password != "":
            try:
                # 输入代理密码
                element_xpath = (
                    '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.widget.EditText[5]')
                elem = self.driver.find_element("xpath", element_xpath)
                if elem.is_enabled() and elem.get_attribute("focusable") == "true":
                    elem.click()
                    elem.clear()
                    elem.send_keys("h5652dk8kj1r")
                    print("✅ 输入成功：127.0.0.1:1080")
                else:
                    print("⚠️ 该文本框不可输入")
            except:
                print("未找到代理密码输入框")
        # //android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[1]/android.widget.Button[2]
        try:
            save = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[1]/android.widget.Button[2]'
            )))
            save.click()
            print("点击保存代理")
            # 等待并处理权限提示框
        except:
            print("没有找到保存代理按钮")
    def start_proxy(self):
        try:
            # 等待整个父列表加载完成
            parent_xpath = '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View'

            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.XPATH, parent_xpath))
            )

            # 获取父容器下的所有 Switch 元素
            switches = self.driver.find_elements(By.XPATH, f"{parent_xpath}//android.widget.Switch")

            target_keyword =  self.proxy_host+":"+ self.proxy_port #"brd.superproxy.io:33335"
            found = False

            for switch in switches:
                desc = switch.get_attribute("contentDescription")  # 获取 content-desc 属性
                if target_keyword in desc:
                    print(f"✅ 找到匹配的代理: {desc}")
                    switch.click()
                    found = True
                    break

            if not found:
                #add_proxy(proxy_host, proxy_port, username, password, protocol)
                print(f"⚠️ 未找到包含 {target_keyword} 的代理项")

        except TimeoutException:
            print("❌ 等待超时：列表未加载完成")
        except Exception as e:
            print(f"⚠️ 出现异常：{e}")
        # //android.widget.Button[@resource-id="com.android.permissioncontroller:id/permission_allow_button"]

    def click_allow_notify(self):
        try:
            allow_notify = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((
                AppiumBy.XPATH,
                '//android.widget.Button[@resource-id="com.android.permissioncontroller:id/permission_allow_button"]'
            )))
            allow_notify.click()
            print("点击allow notification")
            # 等待并处理权限提示框
        except (TimeoutException, NoSuchElementException):
            print("没有找到allow notification")
    def check_exits_start(self):
        parent_xpath = ("//android.widget.FrameLayout[@resource-id='android:id/content']"
                        "/android.widget.FrameLayout/android.view.View/android.view.View"
                        "/android.view.View/android.view.View/android.view.View[2]")
        try:
            # 等待父容器出现（存在于 DOM 中）
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, parent_xpath))
            )
        except TimeoutException:
            print(f"❌ 等待超时：未出现父容器 {parent_xpath}")
            return "not_exits"

        try:
            # 获取父容器
            parent = driver.find_element(By.XPATH, parent_xpath)
        except NoSuchElementException:
            print("⚠️ 父容器未找到，跳过")
            return "not_exits"

            # 在父容器下查找所有 Switch 元素（或查找所有子元素后过滤 Switch）
            # 方式 A：直接查找 Switch
        switch_xpath = parent_xpath + "//android.widget.Switch"
        switches = driver.find_elements(By.XPATH, switch_xpath)

        if not switches:
            print("ℹ️ 父容器下没有 Switch 元素，跳过")
            return "not_exits"
        keyword = self.proxy_host+":"+ self.proxy_port
        # 遍历所有 switch
        for sw in switches:
            try:
                desc = sw.get_attribute("contentDescription")  # content-desc
            except Exception as e:
                # 获取属性失败，跳过
                print(f"⚠️ 获取 content-desc 出错: {e}")
                continue

            if desc is None:
                continue

            if keyword in desc:
                # 找到目标 switch
                print(f"🔍 找到匹配的 Switch: {desc}")

                # 检查是否已选中（checked 属性或 selected 属性等）
                # 注意：具体属性名可能因 App UI 而异，可打印出来看看
                checked_attr = sw.get_attribute("checked")
                # 也可能是 sw.get_attribute("selected") 或 sw.get_attribute("checked") 返回 "true"/"false"
                if checked_attr and checked_attr.lower() == "true":
                   return "started"
                else:
                    print("⚠️ 尚未选中，准备点击")
                    try:
                        sw.click()
                        self.click_allow_notify()
                        print("✅ 点击完成")
                        return "starting"
                    except Exception as e2:
                        print(f"❌ 点击失败: {e2}")
                        return "starting"

                # 既然找到一个，就可以退出遍历（如果你只关心第一个匹配的）
                break
        else:
            # for 循环结束后，没有 break 的情况
            print(f"⚠️ 未在 Switch 列表中找到包含关键字 '{keyword}' 的项")
            return "not_exits"
if __name__ == '__main__':
    udid = "127.0.0.1:9619"
    caps = {
        "platformName": "Android",
        "automationName": "uiautomator2",
        "udid": udid,
        "appPackage": "cn.ys1231.appproxy",
        "appActivity": "cn.ys1231.appproxy/.MainActivity",
        "noReset": True,
        "chromedriverExecutable": "/root/chromedriver/chromedriver",
        "autoGrantPermissions": True,
        "uiautomator2ServerLaunchTimeout": 120000,  # 增加服务器启动超时
        "adbExecTimeout": 120000,  # 增加ADB执行超时
    }

    driver = webdriver.Remote("http://127.0.0.1:4723", caps)
    # 启动指定 Activity
    driver.start_activity("cn.ys1231.appproxy", "cn.ys1231.appproxy/.MainActivity")
    app_proxy = AppProxy(driver, "brd.superproxy.io", "33335", "brd-customer-hl_c487dc73-zone-datacenter_proxy1", "h5652dk8kj1r", "http")
    res = app_proxy.check_exits_start()
    # if res == "not_exits":
    #     app_proxy.add_proxy()
    for i in range(3):
        res = app_proxy.check_exits_start()
        if res == "starting":
            time.sleep(2)
        elif res == "started":
            print("✅ 代理已启动")
            break
        elif res == "not_exits":
            app_proxy.add_proxy()

    print("结束")
    driver.quit()
